package noveiras;

import java.net.URL;
import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import au.id.jericho.lib.html.Source;

public class ConsolidacaoGUI extends Composite {

	private ScrolledComposite scrolledComposite = null;
	private Composite composite = null;
	private Table table = null;
	private int total = 0;
	private ArrayList<Table> listaTabelas = new ArrayList<Table>();
	private Color defBgColor = null;
	public ConsolidacaoGUI(Composite parent, int style) {
		super(parent, style);
		initialize();
	}

	private void initialize() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.numColumns = 2;
		gridLayout.verticalSpacing = 2;
		createScrolledComposite();
		this.setLayout(gridLayout);
		setSize(new Point(300, 200));
		try {
			gerarTabela("epij","data/epij.txt.html");
			gerarTabela("rankpep","data/rankpep.html");
			gerarTabela("syfpeithi","data/syfpeithi.html");
			gerarTabela("hlabind", "data/hlabind.html");
			gerarTabela("hlabind2", "data/hlabind.html");
		} catch (Exception e) {
			e.printStackTrace();
		}
		pack();
	}

	/**
	 * This method initializes scrolledComposite	
	 *
	 */
	private void createScrolledComposite() {
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;
		scrolledComposite = new ScrolledComposite(this, SWT.NONE);
		scrolledComposite.setLayout(new FillLayout());
		scrolledComposite.setAlwaysShowScrollBars(true);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		createComposite();
		scrolledComposite.setLayoutData(gridData);
		scrolledComposite.setContent(composite);
	}

	/**
	 * This method initializes composite	
	 *
	 */
	private void createComposite() {
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.horizontalSpacing = 2;
		gridLayout1.marginWidth = 2;
		gridLayout1.marginHeight = 2;
		gridLayout1.verticalSpacing = 2;
		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.grabExcessVerticalSpace = true;
		gridData2.verticalAlignment = GridData.FILL;
		GridData gridData1 = new GridData();
		gridData1.horizontalAlignment = GridData.FILL;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.verticalAlignment = GridData.FILL;
		composite = new Composite(scrolledComposite, SWT.NONE);
		composite.setLayout(gridLayout1);

	}

	private void gerarTabela(String nome, String sourceUrlString) throws Exception {

		total+=1;
		if (total%3 == 0) {
			createScrolledComposite();
		}
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.horizontalSpacing = 2;
		gridLayout1.marginWidth = 2;
		gridLayout1.marginHeight = 2;
		gridLayout1.verticalSpacing = 2;

		GridData gridData1 = new GridData();
		gridData1.horizontalAlignment = GridData.FILL;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.heightHint = 200;
		gridData1.verticalAlignment = GridData.FILL;

		Label a = new Label(composite, SWT.NONE);
		a.setText(nome);

		table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLayoutData(gridData1);
		table.setLinesVisible(true);
		if (defBgColor == null)
			defBgColor = table.getBackground();

		ArrayList<String> l = new ArrayList<String>();
		ArrayList<String> linhasTabela = new ArrayList<String>();
		int maior = 0;
		String tmp = null;
		String[] stringTab = null;
		String tmpTab[] = null;

		if (sourceUrlString.indexOf(':')==-1) 
			sourceUrlString="file:"+sourceUrlString;
		Source source=new Source(new URL(sourceUrlString));
		String renderedText=source.getRenderer().toString();
		String[] linhas = renderedText.split("\n");

		//removendo linhas vazias
		for (int i=0; i< linhas.length; i++) {
			if (linhas[i].trim().length() > 0)
				l.add(linhas[i]);
		}

		//verificando qual a linha com maior numero de \t
		//para ser as linhas que vão para a Table
		for (int i=0; i< l.size(); i++) {
			tmp = l.get(i);
			if (tmp.contains("\t")) {
				stringTab = l.get(i).split("\t");
				if (stringTab.length > maior)
					maior = stringTab.length;
			} 
		}


		//passando as informações nos seus devidos locais.
		for (int i=0; i< l.size(); i++) {
			tmp = l.get(i);
			if (tmp.contains("\t")) {
				stringTab = l.get(i).split("\t");

				if (stringTab.length == maior) {
					linhasTabela.add(tmp);
				} else {

				}
			} else {

			}
		}

		//sourcesTabela.put(nome, linhasTabela);

		//adicionando as tabelas.
		for (int i=0;i<linhasTabela.size(); i++) {
			tmp = linhasTabela.get(i);
			tmpTab = tmp.split("\t");

			if (i==0) {
				for (int j=0; j<tmpTab.length; j++) {
					TableColumn column = new TableColumn (table, SWT.NONE);
					if (tmpTab[j].contains("\r")) {
						tmpTab[j] = tmpTab[j].replaceAll("\r", "");
					}
					column.setText(tmpTab[j]);
				}
			} else {
				final TableColumn [] columns = table.getColumns ();
				TableItem item = new TableItem (table, SWT.NONE);
				for (int j=0; j<columns.length; j++) {
					if (tmpTab[j].contains("\r")) {
						tmpTab[j] = tmpTab[j].replaceAll("\r", "");
					}
					item.setText (j, tmpTab[j]);
				}
			}
		}

		final TableColumn [] columns = table.getColumns();
		for (int i=0; i<columns.length; i++) 
			columns[i].pack();

		table.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {
				Table t = (Table)arg0.widget;
				String campo = "";
				boolean tudoCarac = true;
				int coluna=-1;
				int maiorTamanho = -1;
				for (int i=0; i<t.getColumnCount();i++) {
					tudoCarac = true;
					campo = t.getItem(t.getSelectionIndex()).getText(i);
					campo = campo.replaceAll("\t", "").replaceAll(" ", "").trim();
					for (int j=0;j<campo.length();j++)
						if (Character.isLetter(campo.charAt(j)) == false)
							tudoCarac = false;

					if (tudoCarac == true)
						if (campo.length() >= maiorTamanho) {
							maiorTamanho = campo.length();
							coluna = i;
						}
				}
				String txtSelecionado = t.getItem(t.getSelectionIndex()).getText(coluna).replaceAll("\t", "").replaceAll(" ", "").trim();;
				System.out.println("--> "+txtSelecionado);
				buscarEmOutrasTabelas(t, txtSelecionado);
			}
		});
		listaTabelas.add(table);

	}

	private void buscarEmOutrasTabelas(Table tabela, String txtSelecionado) {
		//remover selecao de todas as outras tabelas
		Table tbl = null;
		for (int i=0;i<listaTabelas.size();i++) {
			tbl = listaTabelas.get(i);
			if (tbl != tabela)
				tbl.deselectAll();
		}

		for (int i=0;i<listaTabelas.size();i++) {
			tbl = listaTabelas.get(i);
			for (int k=0; k<tbl.getItemCount(); k++)
				for (int j=0; j<tbl.getColumnCount();j++)
					tbl.getItem(k).setBackground(defBgColor);
		}

		//pesquisar em cada coluna.
		String campo="";
		for (int i=0;i<listaTabelas.size();i++) {
			tbl = listaTabelas.get(i);
			for (int k=0; k<tbl.getItemCount(); k++)
				for (int j=0; j<tbl.getColumnCount();j++) {

					campo = tbl.getItem(k).getText(j);
					campo = campo.replaceAll("\t", "").replaceAll(" ", "").trim();
					if (campo.equals(txtSelecionado)) {
						tbl.getItem(k).setBackground(new Color(this.getDisplay(), 255,150,80));
					}
				}
		}
	}

}
